﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;

//Version 1.1
// 软件置顶

public class InitPinWin : MonoBehaviour
{
	//软件在最前面
	[Tooltip("是否置顶")]
	public bool if_top = false;
	[Tooltip("多长时间置顶一次")]
	public int time = 15;

	[DllImport("User32.dll")]
	private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
	[DllImport("user32.dll")]
	private static extern IntPtr GetForegroundWindow();
	[DllImport("User32.dll")]
	private static extern bool SetForegroundWindow(IntPtr hWnd);
	[DllImport("User32.dll")]
	private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

	// Start is called before the first frame update
	void Start()
	{
#if UNITY_EDITOR
#endif
		if (if_top)
		{
			InvokeRepeating("RunSoftFront", 3, time);
		}
	}

	/// <summary>
	/// 保持软件在最前面
	/// </summary>
	public void RunSoftFront()
	{
		// terrainToolkit用Product Name替换
		string soft_name = Application.productName;
		IntPtr hwnd = FindWindow(null, soft_name);

		// 如果没有找到，则不做任何操作（找不到一般就是apptitle错了）  
		if (hwnd == IntPtr.Zero)
		{
			return;
		}

		IntPtr activeWndHwnd = GetForegroundWindow();

		// 当前程序不是活动窗口，则设置为活动窗口  
		if (hwnd != activeWndHwnd)
		{
			ShowWindowAsync(hwnd, 3);
			SetForegroundWindow(hwnd);
		}
	}

}
